package com.example.common.excel;

import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import jakarta.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class ExcelUtils {

    /**
     * 导出Excel
     *
     * @param response  响应对象
     * @param filename  文件名
     * @param sheetName sheet名
     * @param clazz     Excel实体类
     * @param data      数据列表
     */
    public static <T> void export(HttpServletResponse response, String filename, String sheetName, Class<T> clazz, List<T> data) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String encodedFileName = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");

            // 设置样式
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

            // 导出
            EasyExcel.write(response.getOutputStream(), clazz)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .sheet(sheetName)
                    .doWrite(data);
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }

    /**
     * 导出Excel
     *
     * @param response 响应对象
     * @param filename 文件名
     * @param clazz    Excel实体类
     * @param data     数据列表
     */
    public static <T> void export(HttpServletResponse response, String filename, Class<T> clazz, List<T> data) {
        export(response, filename, "Sheet1", clazz, data);
    }
} 